<!DOCTYPE html>
<html>

<head>
    <title>输液监控平台</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <link rel="stylesheet" href="./style/index.css" />
    <script src="./js/vue.global.js"></script>
    <script src="./js/element-plus.js"></script>
    <script src="./js/crypto-js.min.js"></script>
    <script src="./js/axios.min.js"></script>

    <style>
        .title {
            color: red;
            font-size: 44px;
        }

        .demo-form-inline .el-input {
            --el-input-width: 480px;
        }

        .demo-form-inline .el-select {
            --el-select-width: 220px;
        }

        .func_container {
            flex: 6;
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            overflow: auto;
            /* justify-content: space-around; */
        }

        .item_container {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            padding: 60px;
            margin: 10px 10px;
            width: 300px;
            height: 320px;
            text-align: center;
            border-radius: 5px;
            border: 1px solid gray;
        }

        .messge_container {
            flex: 4;
            max-width: 30%;
            display: flex;
            flex-direction: column;
            flex-wrap: wrap;
            height: 100vh;
            background-color: whitesmoke;
            border: 1px solid gray;
            border-radius: 5px;
            padding: 10px;
        }

        .message_item {
            width: 100%;
            word-wrap: break-word;
            overflow-wrap: break-word;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
        }

        /* 模态框内容样式 */
        .modal-content {
            width: 60%;
            background-color: #fefefe;
            margin: 10% auto;
            padding: 20px;
            border: 1px solid #888;
        }

        /* 关闭按钮样式 */
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }

        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }
    </style>
</head>

<body>

    <div id="app">
        <h1 class="title">输液监控平台</h1>
        <el-form :inline="true" :model="robotData" class="demo-form-inline">
            <el-form-item label="设备二维码: ">
                <el-input v-model="robotData.robotCode" placeholder="" clearable />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="query">查询</el-button>
            </el-form-item>
        </el-form>

        <!-- <el-button @click="test">测试</el-button> -->

        <el-dialog v-model="centerDialogVisible" title="提示" width="500" center>
            <span>
                {{ message }}
            </span>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="centerDialogVisible = false">确认</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 往容器里添加子节点 -->
        <div id="list" class="func_container">

        </div>
    </div>

    <script>
        const { createApp, ref } = Vue
        const { ElLoading, ElMessage } = ElementPlus
        var loading = null

        const app = createApp({
            setup() {
                const centerDialogVisible = ref(false)
                const message = ref("")
                const robotData = ref({
                    key: "l8hI1TJfjxiUWSPs",
                    keyId: "2+DmyLnYl2WypAfMghaS8w==",
                    robotCode: 'ROBOT_9020ab3797670000000038FFD20530574D3123602043'
                })
                return {
                    centerDialogVisible,
                    message,
                    robotData
                }
            },
            methods: {
                showMsg(errMsg) {
                    ElMessage(errMsg)
                },
                openFullScreen2() {
                    loading = ElLoading.service({
                        lock: true,
                        text: '加载中...',
                        background: 'rgba(0, 0, 0, 0.7)',
                    })
                },

                closeLoadding() {
                    if (loading != null) {
                        loading.close()
                    }
                },

                uint8ArrayToString() {
                    let str = '';
                    for (let i = 0; i < uint8Array.length; i++) {
                        str += String.fromCharCode(uint8Array[i]);
                    }
                    return str;
                },

                // 加密函数
                encryptData(data, key) {
                    console.log("key: " + key)
                    const sKey = CryptoJS.enc.Utf8.parse(key);
                    const sValue = CryptoJS.enc.Utf8.parse(data);
                    const encrypted = CryptoJS.AES.encrypt(sValue, sKey, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
                    return encrypted.toString();
                },

                // 解密函数
                decryptData(encryptedData, key) {
                    const sKey = CryptoJS.enc.Utf8.parse(key);
                    const decrypt = CryptoJS.AES.decrypt(encryptedData, sKey, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
                    const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
                    return decryptedStr.toString();
                },

                // 测试加解密
                testCrypto() {
                    const timestamp = Date.now();
                    console.log(timestamp); // 输出例如：1611815042339

                    var key = "l8hI1TJfjxiUWSPs"
                    var encodeData = this.encryptData("" + timestamp, key);
                    console.log("Encrypted data base64: " + encodeData)

                    // 解密测试
                    const decryptedData = this.decryptData(encodeData, key);
                    console.log('Decrypted data:', decryptedData);
                },

                // 测试添加节点
                testAddBottle() {
                    var result = {
                        data: {
                            robotStatus: 0,
                            bottleInfos: [
                                {
                                    "remainTime": 30,
                                    "bottleNumber": 1,
                                    "drugName": "葡萄糖",
                                    "capacity": "250ml",
                                    "remainCapacity": "240ml",
                                    "infusionStatus": 1
                                },
                                {
                                    "remainTime": 20,
                                    "bottleNumber": 2,
                                    "drugName": "营养液",
                                    "capacity": "500ml",
                                    "remainCapacity": "499ml",
                                    "infusionStatus": 1
                                },
                                {
                                    "remainTime": 12,
                                    "bottleNumber": 3,
                                    "drugName": "葡萄糖",
                                    "capacity": "100ml",
                                    "remainCapacity": "99ml",
                                    "infusionStatus": 1
                                }
                            ]
                        }
                    }
                    var listDiv = document.getElementById("list")
                    while (listDiv.firstChild) {
                        listDiv.removeChild(listDiv.firstChild); // 循环删除该 div 的第一个子节点，直到没有子节点为止
                    }

                    var robotStatus = result.data.robotStatus
                    if (robotStatus == 0) {
                        // alert("输液机器人发生报警，请及时处理")
                        this.message = "输液机器人发生报警，请及时处理"
                        this.centerDialogVisible = true
                    }

                    var bottleInfos = result.data.bottleInfos
                    for (let i = 0; i < bottleInfos.length; i++) {
                        var infusionBottle = bottleInfos[i]
                        //console.log(infusionBottle)
                        var remainTime = infusionBottle.remainTime

                        var child = document.createElement('div');
                        child.className = "item_container"

                        var bottleIndexView = document.createElement("h2")
                        bottleIndexView.textContent = "瓶号: " + "第" + infusionBottle.bottleNumber + "瓶"

                        var drugNameView = document.createElement("h3")
                        drugNameView.textContent = "名称： " + infusionBottle.drugName

                        var drugCapacityView = document.createElement("h3")
                        drugCapacityView.textContent = "容量: " + infusionBottle.capacity + "ml"

                        var remainCapacityView = document.createElement("h3")
                        if (infusionBottle.remainCapacity != null) {
                            remainCapacityView.textContent = "剩余容量: " + infusionBottle.remainCapacity + "ml"
                        }

                        if (remainTime != null) {
                            var remainTimeView = document.createElement("h3")
                            var duration = ""
                            var hour = Math.floor(remainTime / 3600)
                            if (hour < 10) {
                                duration += "0" + hour
                            } else {
                                duration += hour
                            }
                            duration += ":"

                            var minute = Math.floor((remainTime % 3600) / 60)
                            if (minute < 10) {
                                duration += "0" + minute
                            } else {
                                duration += minute
                            }
                            duration += ":"

                            var seconds = Math.floor(remainTime % 60)
                            if (seconds < 10) {
                                duration += "0" + seconds
                            } else {
                                duration += seconds
                            }
                            remainTimeView.textContent = "剩余时间: " + duration
                        }

                        var infusionStatusView = document.createElement("h3")
                        if (infusionBottle.infusionStatus == 0) {
                            infusionStatusView.textContent = "状态: 待输液"
                        }
                        else if (infusionBottle.infusionStatus == 1) {
                            infusionStatusView.textContent = "状态: 输液中"
                        }
                        else if (infusionBottle.infusionStatus == 2) {
                            infusionStatusView.textContent = "状态: 暂停输液"
                        }
                        else if (infusionBottle.infusionStatus == 3) {
                            infusionStatusView.textContent = "状态: 输液完成"
                        }

                        child.appendChild(bottleIndexView)  // 瓶号
                        child.appendChild(drugNameView)     // 药品名称
                        child.appendChild(drugCapacityView) // 药品容量
                        if (infusionBottle.remainCapacity != null) {
                            child.appendChild(remainCapacityView) // 药品剩余容量
                        }

                        if (infusionBottle.remainTime != null) {
                            child.appendChild(remainTimeView)   // 剩余时间
                        }

                        child.appendChild(infusionStatusView) // 输液状态


                        listDiv.appendChild(child)
                    }
                },

                // 更新ui
                updateUi(result) {
                    var listDiv = document.getElementById("list")
                    while (listDiv.firstChild) {
                        listDiv.removeChild(listDiv.firstChild); // 循环删除该 div 的第一个子节点，直到没有子节点为止
                    }

                    var robotStatus = result.data.robotStatus
                    if (robotStatus == 0) {
                        this.message = "输液机器人发生报警，请及时处理"
                        this.centerDialogVisible = true
                    }

                    var bottleInfos = result.data.bottleInfos
                    for (let i = 0; i < bottleInfos.length; i++) {
                        var infusionBottle = bottleInfos[i]
                        //console.log(infusionBottle)
                        var remainTime = infusionBottle.remainTime

                        var child = document.createElement('div');
                        child.className = "item_container"

                        var bottleIndexView = document.createElement("h2")
                        bottleIndexView.textContent = "瓶号: " + "第" + infusionBottle.bottleNumber + "瓶"

                        var drugNameView = document.createElement("h3")
                        drugNameView.textContent = "名称： " + infusionBottle.drugName

                        var drugCapacityView = document.createElement("h3")
                        drugCapacityView.textContent = "容量: " + infusionBottle.capacity + "ml"

                        var remainCapacityView = document.createElement("h3")
                        if (infusionBottle.remainCapacity != null) {
                            remainCapacityView.textContent = "剩余容量: " + infusionBottle.remainCapacity + "ml"
                        }

                        if (remainTime != null) {
                            var remainTimeView = document.createElement("h3")
                            var duration = ""
                            var hour = Math.floor(remainTime / 3600)
                            if (hour < 10) {
                                duration += "0" + hour
                            } else {
                                duration += hour
                            }
                            duration += ":"

                            var minute = Math.floor((remainTime % 3600) / 60)
                            if (minute < 10) {
                                duration += "0" + minute
                            } else {
                                duration += minute
                            }
                            duration += ":"

                            var seconds = Math.floor(remainTime % 60)
                            if (seconds < 10) {
                                duration += "0" + seconds
                            } else {
                                duration += seconds
                            }
                            remainTimeView.textContent = "剩余时间: " + duration
                        }

                        var infusionStatusView = document.createElement("h3")
                        if (infusionBottle.infusionStatus == 0) {
                            infusionStatusView.textContent = "状态: 待输液"
                        }
                        else if (infusionBottle.infusionStatus == 1) {
                            infusionStatusView.textContent = "状态: 输液中"
                        }
                        else if (infusionBottle.infusionStatus == 2) {
                            infusionStatusView.textContent = "状态: 暂停输液"
                        }
                        else if (infusionBottle.infusionStatus == 3) {
                            infusionStatusView.textContent = "状态: 输液完成"
                        }

                        child.appendChild(bottleIndexView)  // 瓶号
                        child.appendChild(drugNameView)     // 药品名称
                        child.appendChild(drugCapacityView) // 药品容量
                        if (infusionBottle.remainCapacity != null) {
                            child.appendChild(remainCapacityView) // 药品剩余容量
                        }

                        if (infusionBottle.remainTime != null) {
                            child.appendChild(remainTimeView)   // 剩余时间
                        }

                        child.appendChild(infusionStatusView) // 输液状态


                        listDiv.appendChild(child)
                    }
                },

                // 加载输液数据
                loadInfusionBottles() {
                    const timestamp = Date.now();
                    var key = this.robotData.key
                    var encodeData = this.encryptData("" + timestamp, key)

                    // 请求体内容
                    var body = { "robotCode": this.robotData.robotCode };

                    // 发送 POST 请求
                    axios({
                        method: 'GET',
                        url: 'http://120.79.181.201/server/infusion/robot/getInfoByRobotCode?robotCode=' + this.robotData.robotCode,
                        headers: {
                            "keyId": "2+DmyLnYl2WypAfMghaS8w==",
                            "timeMillis": encodeData,
                            'Content-Type': 'application/json'
                        }
                    })
                        .then(response => {
                            console.log("收到服务器响应:")
                            console.dir(result)
                            this.closeLoadding()
                            this.updateUi(result)
                        })
                        .catch(error => {
                            this.closeLoadding()
                            this.showMsg("网络异常")
                            console.log(error);
                        })
                },

                // 查询
                query() {
                    var robotCode = this.robotData.robotCode
                    var start = robotCode.substring(0, 6)
                    if ("ROBOT_" !== start && robotCode.length !== 50) {
                        this.message = "输入的机器码不正确"
                        this.centerDialogVisible = true
                        return
                    }

                    this.openFullScreen2()

                    var listDiv = document.getElementById("list")
                    while (listDiv.firstChild) {
                        listDiv.removeChild(listDiv.firstChild); // 循环删除该 div 的第一个子节点，直到没有子节点为止
                    }

                    // 重新加载
                    this.loadInfusionBottles()
                }

            },
            mounted() {
                console.log("mounted")
                // this.loadInfusionBottles()
                // setInterval(this.loadInfusionBottles, 3000)

                this.testAddBottle()
            }
        })

        app.use(ElementPlus);
        app.mount("#app");

    </script>
</body>

</html>